#include "personal_space.h"
#include "ui_personal_space.h"
#include "itemwidget.h"
#include "ui_itemwidget.h"
#include "itemwidgetpicture.h"
#include "ui_itemwidgetpicture.h"
#include "QMenu"
#include "QPainter"
#include "QBitmap"
#include "iostream"
#include "QDir"
#include "picture.h"
#include "video.h"
#include "QNetworkRequest"
#include "QNetworkReply"
#include "QApplication"
#include "QJsonParseError"
#include "QJsonArray"
#include "QJsonDocument"
#include "QJsonObject"
#include "QJsonValueRef"


//构造函数
Personal_Space::Personal_Space(QWidget *parent, Person * user)
    : QWidget(parent)
    , ui(new Ui::Personal_Space)
    , user(user)
{   
    ui->setupUi(this);
    //消除窗口边框
    this -> setWindowFlags(Qt::FramelessWindowHint);

    //设置为模态窗口
    this->setWindowModality(Qt::ApplicationModal);

    //setting函数
    setting();

    //刷新函数
    updateDate();


    //连接换页槽函数
    connect(ui->Btn_Homepage,&QPushButton::clicked,this,&Personal_Space::page_Homepage);
    connect(ui->Btn_Vedio,&QPushButton::clicked,this,&Personal_Space::page_Vedios);
    connect(ui->Btn_Pictures,&QPushButton::clicked,this,&Personal_Space::page_Pictures);
    connect(ui->pushButton_More,&QPushButton::clicked,this,&Personal_Space::page_Vedios);
    connect(ui->pushButton_More_2,&QPushButton::clicked,this,&Personal_Space::page_Pictures);

    //请求图片
    // URL
    QString Userid = user->getId();
    QString baseUrl = "http://127.0.0.1:5000/PictureCheck?Userid=" + Userid;
    QUrl url(baseUrl);

    // 构造请求QNetworkRequest
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request.setUrl(url);

    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 发送get请求
    manager->get(request);


    //请求视频
    // URL
    QString vbaseUrl = "http://127.0.0.1:5000/VideoCheck?Userid=" + Userid;
    QUrl vurl(vbaseUrl);

    // 构造请求QNetworkRequest
    QNetworkRequest request1;
    request1.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request1.setUrl(vurl);

    QNetworkAccessManager *manager1 = new QNetworkAccessManager();

    // 发送get请求
    manager1->get(request1);


    //请求完成,获取数据并在槽函数中进行处理
    connect(manager, SIGNAL(finished(QNetworkReply*)), this,SLOT(dealMsg(QNetworkReply*)));
    connect(manager1, SIGNAL(finished(QNetworkReply*)), this,SLOT(dealMsg1(QNetworkReply*)));


    page_Homepage();
    
    //主页“我的视频”
    ui->listWidgetvedio->setResizeMode(QListView::Adjust);
    ui->listWidgetvedio->setViewMode(QListView::IconMode);

    //主页“我的图片”
    ui->listWidgetpicture->setResizeMode(QListView::Adjust);
    ui->listWidgetpicture->setViewMode(QListView::IconMode);

    //“我的视频”页面
    ui->listWidget1->setResizeMode(QListView::Adjust);
    ui->listWidget1->setViewMode(QListView::IconMode);

    //“我的图片”页面
    ui->listWidget2->setResizeMode(QListView::Adjust);
    ui->listWidget2->setViewMode(QListView::IconMode);
}

//析构函数
Personal_Space::~Personal_Space()
{
    delete ui;
}

//解析数据给“图片”和主页“我的图片”
void Personal_Space::dealMsg(QNetworkReply *reply)
{
    QByteArray array = reply->readAll();
    QJsonParseError error;
    QJsonDocument data = QJsonDocument::fromJson(array,&error);
    if(!data.isNull())
    {
        QJsonArray obj = data.array();
        for(int i = 0; i < obj.size(); i++)
        {
           QJsonObject object = obj[i].toObject();
           Picture *p = new Picture();
           p->Pictureid = object["pid"].toInt();
           p->Picturename = object["pname"].toString();
           p->Ppath = object["path"].toString();
           AddItem1(p->Pictureid,p->Picturename,p->Ppath);
           if(i < 3)
           {
               AddItempicture(p->Pictureid,p->Picturename,p->Ppath);
           }
        }
    }
}

//解析数据给“视频”和主页“我的视频”
void Personal_Space::dealMsg1(QNetworkReply( *reply1))
{
    QByteArray array = reply1->readAll();
    QJsonParseError error;
    QJsonDocument data = QJsonDocument::fromJson(array,&error);
    if(!data.isNull())
    {
        QJsonArray obj = data.array();
        for(int i = 0; i < obj.size(); i++)
        {
           QJsonObject object = obj[i].toObject();
           Video *v = new Video();
           v->Videoid = object["videoid"].toInt();
           v->Videoname = object["videoname"].toString();
           v->Vpath = object["path"].toString();
           v->Cover = object["cover"].toString();
           AddItem(v->Videoid,v->Videoname,v->Cover,v->Vpath);
           if(i < 3)
           {
               AddItemvedio(v->Videoid,v->Videoname,v->Cover,v->Vpath);
           }
        }
    }
}

//显示头像
QPixmap Personal_Space::PixmapToRound( QPixmap src, int radius)
{
    if(src.isNull())
        return QPixmap();
    QSize size(2*radius, 2*radius);
    QBitmap mask(size);
    QPainter painter(&mask);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
    painter.setBrush(QColor(0, 0, 0));
    painter.drawRoundedRect(0, 0, size.width(), size.height(), 99, 99);
    QPixmap image = src.scaled(size);
    image.setMask(mask);

    return image;
}


//主页界面“我的视频”布局
void Personal_Space::AddItemvedio(const int &qstrid, const QString& qstrFileName, const QString& qstrPic, const QString& qpath)
{
    ItemWidget* pItemWidget = new ItemWidget(this);
    pItemWidget->SetData(qstrid,qstrFileName,qstrPic,qpath);
    QListWidgetItem* pItem = new QListWidgetItem();
    pItem->setSizeHint(QSize(375, 70));
    //设置横纵距离
    ui->listWidgetvedio->setGridSize(QSize(365,220));
    ui->listWidgetvedio->addItem(pItem);
    ui->listWidgetvedio->setItemWidget(pItem, pItemWidget);
    ui->listWidgetvedio->setStyleSheet("QListWidget{padding-left:10px}");
    ui->listWidgetvedio->setFrameShape(QListWidget::NoFrame);
    mainVList.append(pItemWidget);
    connect(pItemWidget, &ItemWidget::rename, this, &Personal_Space::rename_called);
    connect(pItemWidget, &ItemWidget::remake, [=](){
        emit remakePersonalSpace();
    });
}

//主页界面“我的图片”布局
void Personal_Space::AddItempicture(const int &qstrid, const QString& qstrFileName, const QString& qstrPic)
{
    ItemWidgetPicture* pItemWidget = new ItemWidgetPicture(this);
    pItemWidget->SetData(qstrid,qstrFileName,qstrPic);
    QListWidgetItem* pItem = new QListWidgetItem();
    pItem->setSizeHint(QSize(375, 70));
    //设置横纵距离
    ui->listWidgetpicture->setGridSize(QSize(365,220));
    ui->listWidgetpicture->addItem(pItem);
    ui->listWidgetpicture->setItemWidget(pItem, pItemWidget);
    ui->listWidgetpicture->setStyleSheet("QListWidget{padding-left:10px}");
    ui->listWidgetpicture->setFrameShape(QListWidget::NoFrame);
    mainPList.append(pItemWidget);
    connect(pItemWidget, &ItemWidgetPicture::prename, this, &Personal_Space::prename_called);
    connect(pItemWidget, &ItemWidgetPicture::remake, [=](){
        emit remakePersonalSpace();
    });
}

//设置“我的视频”页面格式
void Personal_Space::AddItem(const int &qstrid, const QString& qstrFileName, const QString& qstrPic, const QString& qpath)
{
    ItemWidget* pItemWidget = new ItemWidget(this);
    pItemWidget->SetData(qstrid,qstrFileName,qstrPic,qpath);
    QListWidgetItem* pItem = new QListWidgetItem();
    pItem->setSizeHint(QSize(375, 70));
    //设置横纵距离
    ui->listWidget1->setGridSize(QSize(355,270));
    ui->listWidget1->addItem(pItem);
    ui->listWidget1->setItemWidget(pItem, pItemWidget);
    ui->listWidget1->setStyleSheet("QListWidget{padding-left:10px;padding-top:25px}");
    VList.append(pItemWidget);
    connect(pItemWidget, &ItemWidget::rename, this, &Personal_Space::rename_called);
    connect(pItemWidget, &ItemWidget::remake, [=](){
        emit remakePersonalSpace();
    });
}

//设置“我的图片”页面格式
void Personal_Space::AddItem1(const int &qstrid, const QString &qstrFileName, const QString &qstrPic)
{
    ItemWidgetPicture* pItemWidget = new ItemWidgetPicture(this);
    pItemWidget->SetData(qstrid,qstrFileName,qstrPic);
    QListWidgetItem* pItem = new QListWidgetItem();
    pItem->setSizeHint(QSize(375, 70));

    ui->listWidget2->setGridSize(QSize(355,270));
    ui->listWidget2->addItem(pItem);
    ui->listWidget2->setItemWidget(pItem, pItemWidget);
    ui->listWidget2->setStyleSheet("QListWidget{padding-left:0px;padding-top:25px}");
    PList.append(pItemWidget);
    connect(pItemWidget, &ItemWidgetPicture::prename, this, &Personal_Space::prename_called);
    connect(pItemWidget, &ItemWidgetPicture::remake, [=](){
        emit remakePersonalSpace();
    });
}

//对控件进行美化编辑
void Personal_Space::setting()
{
    //鼠标移动到按钮上时，鼠标样式变为手型
    ui->Btn_Homepage->setCursor(QCursor(Qt::PointingHandCursor));
    ui->Btn_Vedio->setCursor(QCursor(Qt::PointingHandCursor));
    ui->Btn_Pictures->setCursor(QCursor(Qt::PointingHandCursor));
    ui->pushButton_More->setCursor(QCursor(Qt::PointingHandCursor));
    ui->pushButton_More_2->setCursor(QCursor(Qt::PointingHandCursor));
}


//窗口移动
//重写鼠标点击函数
void Personal_Space::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::LeftButton && e->y() < ui->widget_menu->height())
        clickPos=e->pos();
}
//重写鼠标移动函数
void Personal_Space::mouseMoveEvent(QMouseEvent *e)
{
    if(e->buttons()&Qt::LeftButton && e->y() < ui->widget_menu->height())
        move(e->pos()+pos()-clickPos);
}

//槽函数
//“主页”跳转槽函数
void Personal_Space::page_Homepage()
{
    ui -> stackedWidget_Function -> setCurrentIndex(0);
    ui->Btn_Homepage->setFocus();
    ui->Btn_Homepage->setDown(true);
    ui->Btn_Vedio->setDown(false);
    ui->Btn_Pictures->setDown(false);
}
//“视频”跳转槽函数
void Personal_Space::page_Vedios()
{
    ui -> stackedWidget_Function -> setCurrentIndex(1);
    ui->Btn_Vedio->setFocus();
    ui->Btn_Homepage->setDown(false);
    ui->Btn_Vedio->setDown(true);
    ui->Btn_Pictures->setDown(false);
}
//“图片”跳转槽函数
void Personal_Space::page_Pictures()
{
    ui -> stackedWidget_Function -> setCurrentIndex(2);
    ui->Btn_Pictures->setFocus();
    ui->Btn_Homepage->setDown(false);
    ui->Btn_Vedio->setDown(false);
    ui->Btn_Pictures->setDown(true);
}


void Personal_Space::updateDate()
{
    ui->label_Head->setPixmap(PixmapToRound(user->getPixmap(),55));
    ui->label_Name->setText(user->getName());
    ui->label_introduce->setText(user->getSignature());
}

void Personal_Space::rename_called(int VId, QString VName)
{
    for(int i = 0; i < mainVList.size(); i++)
    {
        if(mainVList.at(i)->videoid == VId)
        {
            mainVList.at(i)->ui->lineEdit_info->setText(VName);
        }
    }
    for(int i = 0; i < VList.size(); i++)
    {
        if(VList.at(i)->videoid == VId)
        {
            VList.at(i)->ui->lineEdit_info->setText(VName);
        }
    }
}

void Personal_Space::prename_called(int PId, QString PName)
{
    for(int i = 0; i < mainPList.size(); i++)
    {
        if(mainPList.at(i)->qstrid == PId)
        {
            mainPList.at(i)->ui->lineEdit_pinfo->setText(PName);
        }
    }
    for(int i = 0; i < PList.size(); i++)
    {
        if(PList.at(i)->qstrid == PId)
        {
            PList.at(i)->ui->lineEdit_pinfo->setText(PName);
        }
    }
}
